package com.edu.neusoft.student.controller;

import com.edu.neusoft.student.domain.Salesperson;
import com.edu.neusoft.student.service.SalespersonService;
import com.edu.neusoft.student.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/salespersons")
@Api(tags = "Salesperson Management API", description = "Operations related to salesperson management")
@Validated
public class SalespersonController {

    @Autowired
    private SalespersonService salespersonService;

    // 根据ID获取销售人员信息
    @GetMapping("/{salespersonid}")
    @ApiOperation(value = "Get salesperson by ID", notes = "Retrieve a salesperson by their ID")
    public AjaxResult getSalespersonById(@PathVariable Integer salespersonid) {
        Salesperson salesperson = salespersonService.selectByPrimaryKey(salespersonid);
        if (salesperson != null) {
            return AjaxResult.success("Salesperson retrieved successfully", salesperson);
        } else {
            return AjaxResult.error("Salesperson not found");
        }
    }

    // 添加销售人员信息
    @PostMapping
    @ApiOperation(value = "Add new salesperson", notes = "Create a new salesperson in the system")
    public AjaxResult addSalesperson(@Valid @RequestBody Salesperson salesperson) {
        int result = salespersonService.insert(salesperson);
        if (result > 0) {
            return AjaxResult.success("Salesperson added successfully");
        } else {
            return AjaxResult.error("Failed to add salesperson");
        }
    }

    // 更新销售人员信息
    @PutMapping("/{salespersonid}")
    @ApiOperation(value = "Update salesperson information", notes = "Update an existing salesperson's details by their ID")
    public AjaxResult updateSalesperson(@PathVariable Integer salespersonid, @Valid @RequestBody Salesperson salesperson) {
        salesperson.setSalespersonid(salespersonid); // 设置更新的ID
        int result = salespersonService.updateByPrimaryKey(salesperson);
        if (result > 0) {
            return AjaxResult.success("Salesperson updated successfully");
        } else {
            return AjaxResult.error("Failed to update salesperson");
        }
    }

    // 删除销售人员信息
    @DeleteMapping("/{salespersonid}")
    @ApiOperation(value = "Delete salesperson", notes = "Delete a salesperson by their ID")
    public AjaxResult deleteSalesperson(@PathVariable Integer salespersonid) {
        int result = salespersonService.deleteByPrimaryKey(salespersonid);
        if (result > 0) {
            return AjaxResult.success("Salesperson deleted successfully");
        } else {
            return AjaxResult.error("Failed to delete salesperson");
        }
    }
}
